#include <stdint.h>
#include "stm32f4xx_hal.h"

typedef struct
{
	DAC_HandleTypeDef hdac1;
	GPIO_TypeDef *gpio;
	uint16_t pin;
	DAC_TypeDef *dacx;
	uint16_t channel;
} DACInfo_t;

static DACInfo_t g_DACInfo = {{0}, GPIOA, GPIO_PIN_4, DAC, DAC_CHANNEL_1};

/**
***********************************************************
* @brief LED硬件初始化
* @param
* @return 
***********************************************************
*/
void DAC_DrvInit(void)
{	
	__HAL_RCC_DAC_CLK_ENABLE();
	
	g_DACInfo.hdac1.Instance = g_DACInfo.dacx;
	HAL_DAC_Init(&g_DACInfo.hdac1);
	
	DAC_ChannelConfTypeDef sConfig = { 0 };
	sConfig.DAC_OutputBuffer = DAC_OUTPUTBUFFER_DISABLE; // 不使能输出缓冲
	sConfig.DAC_Trigger = DAC_TRIGGER_NONE; // 不使用触发功能
	HAL_DAC_ConfigChannel(&g_DACInfo.hdac1, &sConfig, g_DACInfo.channel);
	
	GPIO_InitTypeDef GPIO_Init = { 0 };
	// 时钟初始化
	__HAL_RCC_GPIOA_CLK_ENABLE();
	
	// 配置模拟输出
	GPIO_Init.Mode = GPIO_MODE_ANALOG;
	GPIO_Init.Pull = GPIO_NOPULL;
	GPIO_Init.Speed = GPIO_SPEED_FREQ_LOW;
	GPIO_Init.Pin = g_DACInfo.pin; // 引脚配置	
	HAL_GPIO_Init(g_DACInfo.gpio, &GPIO_Init); // 初始化
}

/**
***********************************************************
* @brief 设置DAC输出值
* @param val: DAC数值，范围0-4095
* @return 
***********************************************************
*/
void DAC_SetValue(uint32_t val)
{
	if(val > 4095)
		return;
	
	HAL_DAC_SetValue(&g_DACInfo.hdac1, g_DACInfo.channel, DAC_ALIGN_12B_R, val);
}

/**
***********************************************************
* @brief 设置DAC状态
* @param status: 1表示启动DAC，0表示停止DAC
* @return 
***********************************************************
*/
void DAC_SetStatus(uint8_t status)
{
	if(status > 1)
		return;
	
	if(status)
		HAL_DAC_Start(&g_DACInfo.hdac1, g_DACInfo.channel);
	else
		HAL_DAC_Stop(&g_DACInfo.hdac1, g_DACInfo.channel);
}

/**
***********************************************************
* @brief 获取DAC输出的原始值
* @param 
* @return 返回DAC输出的数值，0-4095
***********************************************************
*/
uint32_t DAC_GetDigitalVal(void)
{
	return HAL_DAC_GetValue(&g_DACInfo.hdac1, g_DACInfo.channel);
}
